import random
import json
import uuid
import datetime
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse

# 自己写的小插件
from app01.forms.account import *
from app01 import models

import os
from django.http import HttpResponse, Http404, FileResponse, StreamingHttpResponse

def test(request):
    response = StreamingHttpResponse("a,b,c\r\nx,f,m")
    response['content_type'] = "application/octet-stream"
    response['Content-Disposition'] = 'attachment; filename=' + os.path.basename('G:/sass/manage.csv')
    return response















def register(request):
    """用户注册"""
    if request.method == 'POST':
        obj = RegisterForm(request.POST)
        if obj.is_valid():
            obj.cleaned_data.pop('confirm_password')
            obj.cleaned_data.pop('code')
            models.Userinfo.objects.create(**obj.cleaned_data)
            user_obj = models.Userinfo.objects.filter(phone_num=obj.cleaned_data.get('phone_num')).first()
            policy_obj = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
            # 创建交易记录
            models.Transaction.objects.create(
                status=2,
                order=str(uuid.uuid4()),
                user=user_obj,
                price_policy=policy_obj,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now(),
            )
            return JsonResponse({'status': True, 'data': '/app01/login/'})
        return JsonResponse({'status': False, 'error': obj.errors})
    obj = RegisterForm()
    return render(request, 'register.html', {'obj': obj})

def login_sms(request):
    """手机短信登录"""
    if request.method == 'GET':
        obj = LoginSmsForm()
        return render(request, 'login_sms.html', {'obj': obj})
    obj = LoginSmsForm(request.POST)
    if obj.is_valid():
        user_obj = models.Userinfo.objects.filter(phone_num=request.POST.get('phone_num')).first()
        request.session['user_id'] = user_obj.id
        request.session.set_expiry(60*60*24)
        return JsonResponse({'status': True, 'data': '/app01/index/'})
    return JsonResponse({'status': False, 'error': obj.errors})

def login(request):
    """用户名登录"""
    # print(request.META.get('REMOTE_ADDR'))
    if request.method == 'GET':
        obj = LoginForm(request)
        return render(request, 'login.html', {'obj': obj})
    obj = LoginForm(request, request.POST)
    if obj.is_valid():
        user_obj = models.Userinfo.objects.filter(username=request.POST.get('username')).first()
        request.session['user_id'] = user_obj.id
        request.session.set_expiry(60*60*24)
        return redirect('/app01/index/')
    return render(request, 'login.html', {'obj': obj})

def logout(request):
    request.session.flush()
    return redirect('/app01/index/')

def sms(request):
    obj = SmsForm(request, request.POST)
    if obj.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': obj.errors})

def image(request):
    """生成图片验证码"""
    from io import BytesIO
    from scripts import image_code
    image_object, code = image_code.check_code()
    request.session['image_code'] = code
    request.session.set_expiry(60)
    # 写入内存(Python3)
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())
